package czk.concrent.protectpause.prictice;

/**
 * 保护性暂停的实现
 * @Author:ChenZhangKun
 * @Date: 2020/9/24 23:39
 */
public class ProtectPausePractice {
    private String obj;

    /**
     * 保护性暂停的实现
     * @param waitTime
     * @return
     */
    public Object pause(long waitTime){
        // 当前时间
        long currentTimeMillis = System.currentTimeMillis();
        // 精力的时间
        long passTime=0;
        while (obj==null){
            if (passTime>waitTime){
                System.out.println("不等了");
                break;
            }
            // 等待
            synchronized (this){
                try {
                    // 设置等待时间
                    this.wait(waitTime-passTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passTime=System.currentTimeMillis()-currentTimeMillis;
            }
        }
        return obj;
    }
    /**
     * 保护性暂停的结束
     */
    public void stop(Object object){
        synchronized (this){
            this.obj=obj;
            this.notifyAll();
            System.out.println("唤醒全部线程");
        }
    }
}
